<?php
namespace Modules\Order\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Order\Entities\UnionOrder;
use Modules\Product\Entities\Sku;

use Modules\Activity\Entities\Seckill\Activity as Seckill;

use Modules\Order\Entities\BaseOrder as Order;
use Modules\Order\Entities\ProductOrder;
use Modules\Activity\Entities\Activity;
use Modules\User\Entities\UserGroupPrice;
use Stbz\Api\SupplyClient;

use Validator;
use ThrowException;
use Auth;
use DB;
use Setting;

class OrderController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $options = $req->all();
        $options['with'] = ['skus', 'aftersale'];
        $options['where'] = [
            'user_id' => $user->id,
            'user_deleted_at' => NULL
        ];

        $options['scopes'] = ['displayAtClient'];

        // $options['scopes'] = ['paid'];

        $options['only'] = [
            'id',
            'uuid',
            'number',
            'user_remark',
            'pay_money_price',
            'pay_score_price',
            'order_money_price',
            'order_score_price',
            'created_at',
            'product_total',
            'sku_total',
            'union_status',
            'union_status_text',
            'auto_closed_at',
            'is_refund_disabled',
            'is_closeable',
            'is_chip_cover',
            'type',
            'activity_type',
            'aftersale' =>  [
                'id',
                'uuid',
                'union_status',
                'union_status_text'
            ],
            'skus' => [
                '*' => [
                    'sku_id',
                    'title',
                    'thumb',
                    'product_type',
                    'money_price',
                    'score_price',
                    'discount_money_price',
                    'discount_score_price',
                    'attrs',
                    'total'
                ]
            ]
        ];

        $list = Order::getList($options);

        $list->each(function ($item) {
            // 是否可兑换碎片
            $item->is_chip_cover = 0;
            if (@method_exists($item->sku->base_sku, 'getChipCoverStatus')) {
                $item->is_chip_cover = $item->sku->base_sku->getChipCoverStatus();
            }
        });

        return $list->generateListResponse();
    }

    public function show(Request $req, $uuid)
    {
        $user = Auth::requireLoginUser();

        $order = Order::getEntity([
            'uuid' => $uuid,
            'user_id' => $user->id,
            'with' => ['address', 'skus', 'deliver_record', 'aftersale']
        ]);

        // \Log::error('查看订单详情' . $order->number);

        if ($order->type === 'box' && $order->union_status === 'pay_pending') {
        	return [];
        }

        $only = [
            'id',
            'uuid',
            'number',
            'user_remark',
            'product_total',
            'sku_total',
            'product_money_price',
            'product_score_price',
            'carriage',
            'carriage_type',
            'vip_discount',
            'score_discount',
            'score_used',      // 使用积分抵扣的数量
            'coupon_discount',
            'redpack_discount',
            'other_discount',
            'is_closeable',
            'other_discount_remark',
            'order_money_price',
            'order_score_price',
            'pay_money_price',
            'pay_score_price',
            'money_paid_at',
            'delivered_at',
            'completed_at',
            'created_at',
            'closed_at',
            'commented_at',
            'union_status',
            'union_status_text',
            'cover_type',
            'cover_discount',
            'exchange_record_id',
            'exchange_money_discount',
            'exchange_score_discount',
            'aftersale' =>  [
                'id',
                'uuid',
                'union_status',
                'union_status_text'
            ],
            'address' => [
                'country',
                'province',
                'city',
                'district',
                'address',
                'consignee',
                'phone',
            ],
            'remark',
            'skus' => [
                '*' => [
                    'title',
                    'number',
                    'thumb',
                    'weight',
                    'attrs',
                    'money_price',
                    'discount_money_price',
                    'score_price',
                    'discount_score_price',
                    'product_uuid',
                    'product_type',
                    'sku_type',
                    'total',
                    'express_name',
                    'express_number',
                    'supplier_sku',
                ]
            ],
            'deliver_record' => [
                'type',
                'remark',
                'express_name',
                'express_number',
            ]
        ];

        $info = $order->getInfo($only);

        $info['is_offline_useable'] = $order->isOfflineUseable() ? 1 : 0;

        return [
            'info' => $info,
            'eeee'=>11111
        ];
    }

    public function store(Request $req)
    {
        $rule = [
            'skus' => ['required', 'array'],
            // 'address_id' => ['integer']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        // 是否开启商城支付
        if (!@Setting::get('sys_pay_enable')['is_shop_enabled']) {
            ThrowException::Conflict(@Setting::get('sys_pay_enable')['shop_tips'] ?: '系统维护中~');
        }

        $user = Auth::requireLoginUser();
        // 1秒内只能调1次此api
        Auth::limitTimeBeforeProcess($user, 'create_order', 1);

        $isNeedAddress = 0;
        $orders = [];
        $address = NULL;
        $activity = NULL;
        $groupPrice = null;   // 人群专享价

        // 准备秒杀活动，如果有
        if ($req->input('seckill_id')) {
            $seckill = Seckill::getEntity([
                'id' => $req->seckill_id
            ], false);

            // 秒杀是否包括此活动
            if ($seckill->stock === 0) {
                $tips = '活动库存已售罄，将以原价结算';
            }
            elseif ($seckill->union_status === 'pending') {
                $tips = '活动未开始，将以原价结算';
            }
            elseif ($seckill->union_status === 'expired') {
                $tips = '活动已结束，将以原价结算';
            }
            else {
                if ($seckill->user_group && !$seckill->user_group->isPassed($user)) {
                    $tips = '暂不符合秒杀价条件，将以原价结算';
                }
                else {
                    // 活动正常可用
                    $activity = $seckill;
                }
            }
        }

        // 准备人群专享价，如果有
        if ($req->input('group_price_uuid')) {
            $groupPriceTemp = UserGroupPrice::getEntity([
                'uuid' => $req->group_price_uuid
            ]);

            if (!$groupPriceTemp->group || !$groupPriceTemp->group->isPassed($user)) {
                $tips = '暂不符合专享价条件，将以原价结算';
            }
            else {
                // 活动正常可用
                $groupPrice = $groupPriceTemp;
            }
        }

        // 检查所有sku是否可出售
        $skuableMaps = array_map(function($item) use($user, $activity, $groupPrice) {
            $sku = Sku::getEntity([
                'id' => $item['id']
            ]);

            if ($item['total'] === 0) {
                ThrowException::Conflict('购买数量不能为0~');
            }

            $sku->checkCanBuy($user, $item['total']);

            if ($activity) {
                $activity->checkCanBuy($sku, $item['total']) || ThrowException::Conflict('活动库存不足~');
            }

            return [
                'skuable' => $sku,
                'activity' => $activity,
                'group_price' => $groupPrice,
                'total' => $item['total']
            ];
        }, $req->skus);

        // 准备收货地址(如果有)
        $address = $user->getAddress($req->input('address_id'));

        // $unionOrder = UnionOrder::initWith($skuableMaps, $user, $address, $options);

        // 准备优惠券
        $userCoupon = $user->coupons()->valid()->where('id', $req->input('coupon_id'))->first();

        // 计算运费
        list($carriageType, $carriage) = ProductOrder::calcCarriage($skuableMaps);

        $options = [
            'activity' => $activity,
            'carriage' => $carriage,
            'carriage_type' => $carriageType,
            'client_name' => Auth::clientName(),
            'client_type' => Auth::clientType(),
            'os_type' => Auth::osType(),
            'remark' => $req->input('remark'),
            'coupon' => $userCoupon,
            'is_use_redpack' => $req->input('is_use_redpack'),
            'is_use_score' => $req->input('is_use_score'),
            'cover_type' => $req->input('cover_type')
        ];

        DB::beginTransaction();

        $order = ProductOrder::initWith($skuableMaps, $user, $address, $options);

        if ($order->isNeedAddress && !$address)
            ThrowException::Conflict('请选择收货地址');

        $order->createAll();

        // 如果是从购物车页面进来，则需要删除购物车中对应项
        if ($req->input('_source') === 'cart') {
            $skuIds = collect($req->input('skus'))->pluck('id');
            $user->cart_items()->whereIn('sku_id', $skuIds)->forceDelete();
        }

        DB::commit();

        // 返回订单信息
        return $order->generateResponse();
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();
        // 1秒内只能调1次此api
        Auth::limitTimeBeforeProcess($user, 'update_order', 1);

        $order = $user->orders()->where('uuid', $uuid)->first() ?: ThrowException::Conflict('找不到此订单');

        $order = $order->derivedOrder();

        if ($req->type === 'close') {
            $order->closeByUser($req->input('reason'));
        }
        elseif ($req->type === 'close_and_delete') {
            
            $order->closeByUser($req->input('reason'));
            $order->deleteAll();
            // $order->forceDelete();
        }
        elseif ($req->type === 'complete') {
            $order->complete();
        }

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $user = Auth::requireLoginUser();
        
        $order = Order::getEntity([
            'uuid' => $uuid,
            'user_id' => $user->id,
        ]);

        $order->update([
            'user_deleted_at' => now()
        ]);

        return [];
    }

    public function closeReasons(Request $req)
    {
        $list = [
            '大小不合适',
            '信息填写有误',
            '重新下订单',
            '不想买了',
            '下次再买',
        ];

        return [
            'list' => $list
        ];
    }
    public function getDeliverOrder(Request $req){
        // R2206222213145642062419
        $type = $req->input('type');
        $object = $req->input('data');
        //  $object='{"orderGoodsSn":null,"orderSn":"R2206222213145642062419","sku":49179184}';
        // // DB::table('test_log')->insert([
        // //     'content'=>json_encode([$object,$type]),
        // //     ]);
        // if($type=='order.delivery'){//订单发货
             
        //      $data = json_decode(json_encode($object),true);
        //      $orderSn =$data['orderSn'];
        //      $sku = $data['orderSn'];
        // }
        // [{"orderGoodsSn":null,"orderSn":"R2206222213145642062419","sku":49179184},"order.delivery"]
        // $type = 'order.delivery';
        $res = [];
        if($type=='order.delivery'){
            $data = json_decode(json_encode($object),true);
             $orderSn =$data['orderSn'];
             $sku = $data['orderSn'];
            // $orderSn ='R2206222213145642062419';
            //  $sku = '49179184';
             $res = $this->getwuliu($orderSn,$sku);
             $data = [];
             if($res['data']['info']){
                
                if($res['data']['info']['name'] && $res['data']['info']['no']){
                    
                    // $payment_records = DB::table('payment_records')->where('out_trade_number',$orderSn)->first();
                    $orderInfo = DB::table('order_skus')->where('pay_order_number',$orderSn)->first();
                    DB::table('order_skus')->where('id',$orderInfo->id)->update(['express_name'=>$res['data']['info']['name'],'express_number'=>$res['data']['info']['no'],'supplier_sku'=>$sku]);
                    // 
                    // $orderList = DB::table('order_skus')->where('id',$orderInfo->order_id)->get();
                    // if($orderList->isEmpty()){
                        DB::table('orders')->where('id',$orderInfo->order_id)->update(['deliver_status'=>3]);
                    // }
                    
                }
             }
        }
        // exit(['code'=>1]);
       return ['code'=>1,$res];
    }
    public function getwuliu($orderSn,$sku){
        $supplyClient = new SupplyClient('5EAD103672C6BD067A89F75AF998053F183891655452368','941DBE25600BD4BCDF35EF50EE30CD86');
        $param = ['orderSn'=>$orderSn, 'sku'=>$sku];//请求参数source来源：来源0为全部来源1云仓2京东6阿里巴巴7天猫
        $method = 'get';//请求方法
        $action = '/v2/logistic';//请求资源名
        $response = $supplyClient->getApiResponse($method,$action,$param);
        $response = json_decode($response,true);
        return $response;
    }
    //查看物流
    public function getwu11liu($orderSn,$sku){
        $supplyClient = new SupplyClient('5EAD103672C6BD067A89F75AF998053F183891655452368','941DBE25600BD4BCDF35EF50EE30CD86');
        $param = ['orderSn'=>$orderSn, 'sku'=>$sku];//请求参数source来源：来源0为全部来源1云仓2京东6阿里巴巴7天猫
        $method = 'get';//请求方法
        $action = '/v2/logistic';//请求资源名
        $response = $supplyClient->getApiResponse($method,$action,$param);
        $response = json_decode($response,true);
        return $response;
    }
}
